% To calculate avg transition prob & its standardized one
clear all;
clc;
disp('To calculate avg qtrly transition prob & its standardized one');
load TP06_Q_RJ_fin_R5.mat
freqj=4;% 4 quarters
year_list=[1997:2009]';
year_list_text=num2str(year_list);
quarter_list=[1:4]';
quarter_list_text=num2str(quarter_list);
Rate_list=[0,1:0.5:5];
count=zeros(1,1,10,13);
avgprob=zeros(1,1,10,12); % the last column will be 1, so we ignore the 13th column and set it as 12 columns
stdprob=zeros(1,1,9,10);  % We delete rating 0 in rows and columns and delete withdrawn in columns since we set it as zero bcs of standadization
filename='TP06_Q_RJ_fin_R5_avg transition prob.xls';
% filename1='TP06_Q_RJ_fin_transition prob.xls';
% filename2='TP06_Q_RJ_fin_transition prob_std.xls';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%To calculate the average transition prob %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%avg calculate time
yrwant=13; %2009
freqjwant=4;

for i=2:yrwant-1 %1998~2008
    for j=1:4
        count(1,1,:,:) = count(1,1,:,:)+ final_result(i,j,:,:);
    end
end
for i=yrwant:yrwant %2009
    for j=1:freqjwant %Q4
        count(1,1,:,:) = count(1,1,:,:)+ final_result(i,j,:,:);
    end
end
xx(:,:)=count(1,1,:,:);
xlswrite(filename, xx,'counts');
clear xx

for ii=1:length(Rate_list)
    for jj=1:12 % the last column for total is deleted since all of them are 1
        avgprob(1,1,ii,jj)=count(1,1,ii,jj)/count(1,1,ii,13);
    end
end
xx(:,:)=avgprob(1,1,:,:);
xlswrite(filename, xx,'avgprob');
clear xx

for ii=2:length(Rate_list)% the first row for rating of 0 is deleted
    for jj=2:11% the first column for rating of 0, the 12th column for withdraw are deleted
        stdprob(1,1,ii-1,jj-1) = avgprob(1,1,ii,jj)/(1-avgprob(1,1,ii,12));
    end
end
xx(:,:)=stdprob(1,1,:,:);
xlswrite(filename, xx,'stdprob');
clear xx